(function ($) { /** * initializeBlock * * Adds custom JavaScript to the block HTML. * * @date 15/4/19 * @since 1.0.0 * * @param object $block The block jQuery element. * @param object attributes The block attributes (only available when editing). * @return void */ var initializeBlock = function ($block) { function isInViewport() { var pageHeight = $(document).height(); var windowScroll = $(window).scrollTop(); var windowHeight = $(window).height(); var scrollTreshold = windowScroll + (windowHeight * .95); var elementTop = $($block).offset().top; var elementHeight = $($block).outerHeight(); var elementBottom = elementTop + elementHeight; if (elementTop < scrollTreshold && windowScroll < elementBottom) { window.removeEventListener('scroll', initStatCounters); return true; } else { return false; } }; var countDecimals = function (value) { if ((value % 1) != 0) return value.toString().split(".")[1].length; return 0; }; function initStatCounters() { window.addEventListener('scroll', initStatCounters); if (isInViewport() || window.acf) { var animate_start_delay = 200; var animate_start_stagger = 500; // each stat counter delays slightly longer than the last var animate_length = 3000; $('.stat-value[stat-value]').each(function () { var statValue = $(this).attr('stat-value'); statValue = statValue.replace(/,/g, ""); statValue = parseFloat(statValue); var decimals = countDecimals(statValue); $(this).prop('Counter', 0).delay(animate_start_delay).animate({ Counter: statValue }, { duration: animate_length, easing: 'swing', step: function (now) { if (decimals) { $(this).text(now.toFixed(decimals)); } else { $(this).text(Math.ceil(now).toLocaleString('en')); } }, complete: function () { } }); animate_start_delay += animate_start_stagger; }); } } initStatCounters(); } // Initialize each block on page load (front end). setTimeout(function () { $(function () { $('.stat-section').each(function () { initializeBlock($(this)); }); }); }, 1000); // Initialize dynamic block preview (editor). if (window.acf) { window.acf.addAction('render_block_preview/type=stat-section', initializeBlock); } })(jQuery);